/*******************************************************************************
 * Package: com.song.boot.springstudy.netty.http
 * Type:    HttpServerHandler
 * Date:    2023-06-20 21:10
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.Objects;

/**
 * 功能描述： 处理器
 *
 * @author Songxianyang
 * @date 2023-06-20 21:10
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取客户端数据  并发送数据到客户端
     * @param channelHandlerContext
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        // 判断是不是http请求
        if (httpObject instanceof HttpRequest) {
            System.out.println("获取管道得hashcode》》》"+channelHandlerContext.pipeline().hashCode()+"新的处理器》》》》"+this.hashCode());
            HttpRequest msg=  (HttpRequest)httpObject;
            String uri = msg.uri();
            System.out.println("url》》》》"+uri);
            if (Objects.equals(uri, "/favicon.ico")) {
                // url》》》》/favicon.ico  如果 url==/favicon.ico  不处理过滤掉
                return;
            }
            System.out.println("那个类》》》》"+msg.getClass());
            System.out.println("客户端地址》》》》"+channelHandlerContext.channel().remoteAddress());
            // 给客户端发送消息
            ByteBuf clientMsg = Unpooled.copiedBuffer("你好！瑶瑶", CharsetUtil.UTF_8);
            // 构造http响应 遵循http协议
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,clientMsg);
            // 设置返回值类型
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            // 设置长度
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,clientMsg.readableBytes());
            // 发送响应
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
